package com.zysc.processflow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zysc.processflow.common.base.ResultBody;
import com.zysc.processflow.common.util.StringUtils;
import com.zysc.processflow.entity.*;
import com.zysc.processflow.mapper.HandleprocessMapper;
import com.zysc.processflow.mapper.HandlerecordMapper;
import com.zysc.processflow.pojo.HandleprocessPo;
import com.zysc.processflow.pojo.ProcessConfig;
import com.zysc.processflow.service.*;
import com.zysc.processflow.common.base.BaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 处置流程管理 服务实现类
 * </p>
 *
 * @author 正元智慧城市_
 * @since 2022-11-18
 */
@Service
public class HandleprocessServiceImpl extends BaseService<HandleprocessMapper, Handleprocess> implements IHandleprocessService {
    @Autowired
    IHandleprocessnodeService handleprocessnodeService;
    @Autowired
    IHandleprocesslineService handleprocesslineService;
    @Autowired
    IHandleprocessccService handleprocessccService;
    @Autowired
    HandlerecordMapper handlerecordMapper;
    @Autowired
    IOrganizationService organizationService;
    @Override
    public List<HandleprocessPo> GetHandleprocessListByPage(IPage<Handleprocess> page, String name, String processno, String id) {
        LambdaQueryWrapper<Handleprocess> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .like(!StringUtils.isNull(processno), Handleprocess::getProcessno, processno)
                .like(!StringUtils.isNull(name), Handleprocess::getName, name)
                .eq(!StringUtils.isNull(id), Handleprocess::getId, id)
                .orderByDesc(Handleprocess::getUpdatetime);;
        List<Handleprocess> list = new ArrayList<>();
        if (page != null) {
            list = this.baseMapper.selectPage(page, queryWrapper).getRecords();
        }else{
            list = this.baseMapper.selectList(queryWrapper);
        }
        //加上审核步骤和抄送
        List<HandleprocessPo> collect = list.stream().map(item -> {
            HandleprocessPo handleProcessPo = new HandleprocessPo();
            BeanUtils.copyProperties(item, handleProcessPo);
            return handleProcessPo;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public Boolean handleNodes(ProcessConfig entity) {
        boolean b1 = true; //删除成功标志
        boolean b2 = true; //新增成功标记
        String processId = entity.getId();
        //删除所有node
        LambdaQueryWrapper<Handleprocessnode> handleprocessnodeqw = new LambdaQueryWrapper<>();
        handleprocessnodeqw.eq(Handleprocessnode::getProcessid,processId);
        List<Handleprocessnode> list = handleprocessnodeService.list(handleprocessnodeqw);
        if(list.size()>0){
            b1 = handleprocessnodeService.remove(handleprocessnodeqw);
        }
        //新增传来的node
        if(entity.getNodeList().size()>0){
            for (ProcessConfig.NodeConfig el : entity.getNodeList()) {
                Handleprocessnode handleprocessnode = new Handleprocessnode();
                handleprocessnode.setId(el.getId());
                handleprocessnode.setProcessid(processId);
                if (el.getType() != null && el.getType().equals("开始节点")) {
                    handleprocessnode.setIsfirstnode("1");
                } else {
                    handleprocessnode.setIsfirstnode("0");
                }
                handleprocessnode.setNodetype(el.getType());
                handleprocessnode.setRoleid(el.getRoleid());
                handleprocessnode.setNodename(el.getName());
                handleprocessnode.setType(el.getBusinesstype());
                handleprocessnode.setRolename(el.getRolename());
                handleprocessnode.setCustom(el.getCustom());
                handleprocessnode.setNeedsendmsg(el.getNeedsendmsg());

                String disposerid = "";
                String disposername = "";
                String orgid = "";
                String orgname = "";
                try {
                    List<Person> disposerList = el.getPerinfo();
                    if (disposerList.size() > 0) {
                        disposerid = disposerList.get(0).getId();
                        disposername = disposerList.get(0).getName();
                    }
                } catch (Exception e) {

                }
                try {
                    List<Organization> orgList = el.getOrginfo();
                    if (orgList.size() > 0) {
                        orgid = orgList.get(0).getId();
                        orgname = orgList.get(0).getName();
                    }
                } catch (Exception e) {

                }
                handleprocessnode.setDisposerid(disposerid);
                handleprocessnode.setDisposername(disposername);
                handleprocessnode.setOrgid(orgid);
                handleprocessnode.setOrgname(orgname);

                boolean saveOrUpdate = handleprocessnodeService.saveOrUpdate(handleprocessnode);
                if (!saveOrUpdate) {
                    b2 = false;
                    break;
                }
            }
        }
        return b1&&b2;
    }

    @Override
    public Boolean handleCcs(HandleprocessPo entity) {
        boolean b1 = true; //删除成功标志
        boolean b2 = true; //新增成功标记
        String processId = entity.getId();
        //删除所有cc
        LambdaQueryWrapper<Handleprocesscc> handleprocessccqw = new LambdaQueryWrapper<>();
        handleprocessccqw.eq(Handleprocesscc::getProcessid,processId);
        List<Handleprocesscc> list = handleprocessccService.list(handleprocessccqw);
        if(list.size()>0){
            b1 = handleprocessccService.remove(handleprocessccqw);
        }
        //新增cc
        if(entity.getHandleprocessccList().size()>0){
            b2 = handleprocessccService.saveBatch(entity.getHandleprocessccList());
        }
        return b1&&b2;
    }

    @Override
    public Boolean hasRunningRecord(String processID) {
        LambdaQueryWrapper<Handlerecord> handlerecordqw = new LambdaQueryWrapper<>();
        handlerecordqw
                .eq(Handlerecord::getProcessid,processID)
                .eq(Handlerecord::getHandlestatus,"0");
        List<Handlerecord> list = handlerecordMapper.selectList(handlerecordqw);
        if(list.size()>0){
            throw new RuntimeException("当前存在运行中的记录,无法修改该流程!");
        }
        return true;
    }

    @Override
    public Boolean deleteProcessNodes(String id) {
        Boolean b = true;
        LambdaQueryWrapper<Handleprocessnode> handleprocessnodeqw = new LambdaQueryWrapper<>();
        handleprocessnodeqw.eq(Handleprocessnode::getProcessid,id);
        List<Handleprocessnode> handleprocessnodeList = handleprocessnodeService.list(handleprocessnodeqw);
        if(handleprocessnodeList.size()>0){
            b = handleprocessnodeService.remove(handleprocessnodeqw);
        }
        return b;
    }
    @Override
    public Boolean deleteProcessCcs(String id) {
        Boolean b = true;
        LambdaQueryWrapper<Handleprocesscc> handleprocessCcqw = new LambdaQueryWrapper<>();
        handleprocessCcqw.eq(Handleprocesscc::getProcessid,id);
        List<Handleprocesscc> handleprocessCcList = handleprocessccService.list(handleprocessCcqw);
        if(handleprocessCcList.size()>0){
            b = handleprocessccService.remove(handleprocessCcqw);
        }
        return b;
    }

    @Override
    public Boolean handleLines(ProcessConfig entity) {
        boolean b1 = true; //删除成功标志
        boolean b2 = true; //新增成功标记
        String processId = entity.getId();
        //删除所有线
        LambdaQueryWrapper<Handleprocessline> handleprocesslineqw = new LambdaQueryWrapper<>();
        handleprocesslineqw.eq(Handleprocessline::getProcessid,processId);
        List<Handleprocessline> list = handleprocesslineService.list(handleprocesslineqw);
        if(list.size()>0){
            b1 = handleprocesslineService.remove(handleprocesslineqw);
        }
        //新增传来的线
        if(entity.getLineList().size()>0){
            for (ProcessConfig.LineConfig el : entity.getLineList()) {
                Handleprocessline handleprocessline= new Handleprocessline();
                handleprocessline.setProcessid(processId);
                handleprocessline.setSourcenodeid(el.getFrom());
                handleprocessline.setTargetnodeid(el.getTo());
                handleprocessline.setCondition(el.getLabel());
                handleprocessline.setConditiontype(el.getConditiontype());
                handleprocessline.setConditionvalue(el.getConditionvalue());
                boolean saveOrUpdate = handleprocesslineService.saveOrUpdate(handleprocessline);
                if (!saveOrUpdate) {
                    b2 = false;
                    break;
                }
            }
        }
        return b1&&b2;
    }

    @Override
    public Boolean deleteProcessLines(String id) {
        Boolean b = true;
        LambdaQueryWrapper<Handleprocessline> handleprocessLineqw = new LambdaQueryWrapper<>();
        handleprocessLineqw.eq(Handleprocessline::getProcessid,id);
        List<Handleprocessline> handleprocessLineList = handleprocesslineService.list(handleprocessLineqw);
        if(handleprocessLineList.size()>0){
            b = handleprocesslineService.remove(handleprocessLineqw);
        }
        return b;
    }

    @Override
    public ResultBody getConfigByProcessId(String processId) {
        try{
            //1.查找流程
            Handleprocess handleprocess = this.getById(processId);
            //2.获取流程配置(从数据库中每个字段取值,组成config需要的字段,如果缺少的字段,比如top,left[界面上显示的偏移量],从原来的config中获取)
            ProcessConfig config = new ProcessConfig();
            config.setId(processId);
            config.setName(handleprocess.getName());
            config.setProcessno(handleprocess.getProcessno());
            config.setDescription(handleprocess.getDescription());
            config.setType(handleprocess.getType());
            config.setLineList(handleprocesslineService.getLinesConfigByProcessId(processId));
            config.setNodeList(handleprocessnodeService.getNodesConfigByProcessId(processId));
            return ResultBody.Success(config);
        }catch(Exception e){
            return ResultBody.error(e.getMessage(),500);
        }
    }
}
